package com.example.utils;


import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.apache.commons.lang3.tuple.Pair;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @description: 密码加密
 * @author vincez
 * @time 2023/4/13 23:59
 * @version 1.0
 */
public class SaltAESUtil {

    private SaltAESUtil(){
        throw new IllegalStateException("Utility class");
    }

    /**
     * AES对称加密
     * @param encrypt 需要加盐加密的字符串
     * @return 返回 加密结果,加密盐
     */
    public static Pair<String,String> encrypt(String encrypt) {
        Pair<String, String> pair;
        String salt = getSalt(32);
        byte[] bytes = salt.getBytes(StandardCharsets.UTF_8);
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, bytes);
        //加密为16进制表示
        encrypt = aes.encryptHex(encrypt);
        pair = Pair.of(encrypt, salt);
        return pair;
    }


    /**
     * AES 对称解密
     * @param salt 加密盐
     * @param decrypt 需解密的密码
     * @return 返回解密结果
     */
    public static String decrypt(String salt,String decrypt) {
        //构建
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, salt.getBytes(StandardCharsets.UTF_8));
        //解密为字符串
        return aes.decryptStr(decrypt, CharsetUtil.CHARSET_UTF_8);
    }


    /**
     * 获取随机字符串
     * @param n 随机字符串长度
     * @return 返回随机字符串结果
     */
    public static String getSalt(int n){
        char[] chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()_+").toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < n; i++){
            //Random().nextInt()返回值为[0,n)
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }
}
